package com.example.exception;

/**
 * @author zhanghui
 * @date 2021/12/7 10:59
 */
public class ExceptionTest {
    public static void main(String[] args) {
        int i = 10, j = -1;
        try {
            int result = divide(i, j);
            System.out.println(result);
        } catch (DivideByNeg e) {
            System.out.println("捕获自定义异常");
            System.out.println(e.getMessage());
        }
    }

    private static int divide(int i, int j) {
        int result = 0;
        try {
            if (j < 0) {
                throw new DivideByNeg("除数为负数");
            }
            result = i / j;
            return result;
        } catch (ArithmeticException e) {
            System.out.println(e.getMessage());
            return -1;
        } finally {
            System.out.println("计算完成");
        }
    }
}

class DivideByNeg extends RuntimeException {
    public DivideByNeg() {

    }

    public DivideByNeg(String msg) {
        super(msg);
    }
}
